#include "jamod_global.h"
#include "jamod_proxyimport.h"
#include "jamod_filesystem.h"
#include "q_shared.h"

qboolean bDiscoverPluginLog = qfalse;

char **JAModPlugins = NULL;

void JAMod_LoadBasicPluginSettings(void)
{
	bDiscoverPluginLog = JAMod_GetINIBoolean("JAModCore:ActiveAdvancedDiscoveryLog", qfalse);
	if(bDiscoverPluginLog)
	{
		trap_Printf("^7JAMod: ActiveAdvancedDiscoveryLog on. Advanced Logging of plugin discovery on.\n");
	}
}

void JAMod_DiscoverPlugins(void)
{
	int i;
	int pluginsLoaded = 0;
	if(bDiscoverPluginLog)
	{
		trap_Printf("^7JAMod: Plugin discovery...\n");
	}

	for(i = 0; i < JAMod_GetININumSections(); i++)
	{
		char pluginName[MAX_QPATH];
		strcpy(pluginName, JAMod_GetINISectionName(i));
		if(strncmp(pluginName, "JAMod", 5) && strncmp(pluginName, "jamod", 5))
		{
			// Not a JAMod section. Must be a plugin.
			if(bDiscoverPluginLog)
			{
				trap_Printf("^5Plugin disovery: %s\n", pluginName);
			}
			// check whether we have this field enabled
			{
				char sectionName[MAX_QPATH];
				strcpy(sectionName, "Active");
				strcat(sectionName, pluginName);
				if(!JAMod_GetINIBoolean(sectionName, 1))
				{
					if(bDiscoverPluginLog)
					{
						trap_Printf("^7Plugin manually disabled, continuing...\n");
					}
					continue;	// manual disable
				}
			}
			// kk, find the path for it now. TODO: make me into a generalized func, as this seems used a lot
			{
				char buffer[MAX_QPATH];
				trap_Cvar_VariableBuffer("fs_game", buffer, MAX_QPATH);
				strcat(buffer, "/JAMod");
				strcat(buffer, pluginName);
				strcat(buffer,".dll");
				//strcpy(buffer, "JAMod");
				//strcat(buffer, pluginName);
				//strcat(buffer, ".dll");
				if(!LoadLibrary(TEXT(buffer)))
				{
					if(bDiscoverPluginLog)
					{
						trap_Printf("^7VM_Create on JAMod%s.dll failed.\n", pluginName);
					}
					continue; // Don't bother loading.
				}
				else
				{
					pluginsLoaded++;
				}
			}
		}
	}
	if(pluginsLoaded <= 0)
	{
		trap_Printf("^5No plugins found! You may want to install some in order to take full advantage of JAMod.\n");
		return;
	}
	else
	{
		trap_Printf("^2Loaded %i plugins\n", pluginsLoaded);
		return;
	}
}